/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.task;

import com.alibaba.fastjson.JSONObject;
import com.bifrost.constant.OrderType;
import com.bifrost.entity.Order;
import com.bifrost.entity.OrderReturn;
import com.bifrost.entity.RefundRequest;
import com.bifrost.entity.TransactionSendLog;
import com.bifrost.event.TransactionEvent;
import com.bifrost.repository.OrderReturnRepository;
import com.bifrost.repository.OrderTransactionRepository;
import com.bifrost.repository.RefundRequestRepository;
import com.bifrost.service.OrderService;
import com.bifrost.service.PayService;
import com.bifrost.service.ReturnService;
import com.bifrost.uid.UidGenerator;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 *
 *
 *@author joewee
 *@version 1.0.0
 *@Date 2018/3/23 17:21
 */
@Component
@JobHandler("swiftPassRefundTask")
public class SwiftPassRefundTask extends IJobHandler{
    private static Logger LOGGER = LoggerFactory.getLogger(PayService.class);
    @Autowired
    PayService payGatewayService;
    @Autowired
    OrderTransactionRepository orderTransactionRepository;
    @Autowired
    RefundRequestRepository refundRequestRepository;
    @Autowired
    UidGenerator uidGenerator;
    @Autowired
    OrderService orderService;
    @Autowired
    ReturnService returnService;
    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    OrderReturnRepository returnRepository;


    @Override
    public ReturnT<String> execute(String s) throws Exception {
        XxlJobLogger.log("执行退款任务");
        List<RefundRequest> requests = refundRequestRepository.findAllByIsSuccess(Boolean.FALSE);
        if (requests != null && !requests.isEmpty()) {
            for (RefundRequest request : requests) {
                try {
                    //售后单（原始订单非优惠券订单）的库存回滚在退款时进行
                    Order order = orderService.findOrderById(request.getOrderId());
                    if (!Boolean.TRUE.equals(request.isFromOrder())
                            && !OrderType.CASH_BY_COUPON.equalsIgnoreCase(order.getOrderType())) {
                        Long returnid = request.getReturnId();
                        Long orderId = request.getOrderId();
                        LOGGER.info("开始回滚订单相关项：" + orderId);
                        if (returnid == null) {
                            LOGGER.info("找不到对应的售后单：" + returnid);
                        }
                        orderService.rollbackByOrderReturn(returnid);
                    }
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                    continue;
                }
                LOGGER.info("开始执行退款：" + request.getOutTradeNumber());
                try {
                    Order order = orderService.findOrderById(request.getOrderId());
                    Integer refundFee = request.getRefundFee();
                    if (refundFee != null && refundFee > 0) {
                        SortedMap<String, String> map = new TreeMap();
                        request.setRefundNumber("" + uidGenerator.getUID());
                        request.setUpdateTimestamp(new Date());
                        map.put("total_fee", "" + order.getOrderTotal().multiply(BigDecimal.valueOf(100)).intValue());
                        map.put("refund_fee", request.getRefundFee().toString());
                        map.put("out_trade_no", request.getOutTradeNumber());
                        map.put("out_refund_no", request.getRefundNumber());
                        Map<String, String> result = payGatewayService.refund(map);
                        request.setResponse(JSONObject.toJSONString(result));
                        Assert.notNull(result, "退款调用失败");
                        if ("0".equals(result.get("status")) && "0".equals(result.get("result_code"))) {
                            LOGGER.info("退款成功");
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug(String.format("记录订单%s退款交易记录，金额%d分", request.getOutTradeNumber(), request.getRefundFee()));
                            }
                            request.setSuccess(Boolean.TRUE);
                            /**
                             * 发布事件
                             * */
                            TransactionEvent evt = null;
                            if (Boolean.TRUE.equals(request.isFromOrder())) {
                                evt = new TransactionEvent(order, TransactionSendLog.Type.CANCEL);
                            } else {
                                OrderReturn orderReturn = returnRepository.findOne(request.getReturnId());
                                evt = new TransactionEvent(orderReturn, TransactionSendLog.Type.REFUND);
                            }
                            if (evt != null) {
                                applicationContext.publishEvent(evt);
                            }
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug(String.format("订单%s退款交易记录保存成功", request.getOutTradeNumber(), request.getRefundFee()));
                            }
                        } else {
                            LOGGER.info("退款失败：" + result.get("err_msg"));
                            continue;
                        }
                    } else {
                        //退款金额=0时不执行退款
                        request.setSuccess(Boolean.TRUE);
                    }
                    refundRequestRepository.save(request);
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        XxlJobLogger.log("执行退款任务完成");
        return ReturnT.SUCCESS;
    }
}
